<?php

// $Id: management.inc,v 1.9 2008/10/18 18:25:04 silviogutierrez Exp $

/**
 * @file
 * Contains all picture management functions for Gallerix, and all settings pages.
 */
 


/**
 * Provides a display settings page.
 *
 */
function gallerix_display_settings() {

  //Display Options
  $form['gallerix_display'] = array(
    '#type' => 'fieldset',
    '#title' => t('Display Options'),
  );
  $form['gallerix_display']['gallerix_default_view'] = array(
    '#type' => 'select',
    '#title' => t('Default View'),
    '#description' => t("Select which view to default to. Grid view will display all the images in an album. Single View will display the first image of the album, along with thumbnails if enabled below. A link is provided to switch between the two."),
    '#options' => array('grid' => 'Grid', 'viewer' => 'Single'),
    '#default_value' => variable_get('gallerix_default_view', 'grid'),
  );  
  $form['gallerix_display']['gallerix_default_sort'] = array(
    '#type' => 'select',
    '#title' => t('Default Sort Order'),
    '#description' => t("Your album pictures will be displayed in the selected order. You can override this setting individually by selecting a different order in the album creation page."),
    '#options' => array('ascending' => t('Date Taken Ascending'), 'descending' => t('Date Taken Descending'), 'random' => t('Random'), 'filename' => t('Filename'), 'custom' => t('Custom')),
    '#default_value' => variable_get('gallerix_default_sort', 'ascending'),
  );
  $form['gallerix_display']['gallerix_thumbnail_number'] = array(
    '#type' => 'textfield',
    '#title' => t('Number of Thumbnails'),
    '#description' => t('This number controls the amount of thumbnails displayed in each album for browsing. Raising this might decrease performance since there will be more database queries.'),
    '#size' => 2,
    '#default_value' => variable_get('gallerix_thumbnail_number', 5),
  ); 
  $form['gallerix_display']['gallerix_translucence'] = array(
    '#type' => 'checkbox', 
    '#title' => t("Thumbnail Translucence"),
    '#description' => t('When enabled, thumbnails will be made translucent until the mouse hovers over them.'), 
    '#default_value' => variable_get('gallerix_translucence', 1),
  );     
  
  
  $form['gallerix_layout'] = array(
    '#type' => 'fieldset',
    '#tree' => TRUE,
    '#title' => t('Layout Options'),
    '#theme' => 'gallerix_component_settings'
  );
  
  $components = _gallerix_load_components('configure');
  
  foreach($components as $component) {
    $form['gallerix_layout'][$component['#id']]['title'] = array(
      '#type' => 'value',
      '#value' => $component['#title'],    
    );   
    $form['gallerix_layout'][$component['#id']]['weight'] = array(
      '#type' => 'weight',
      '#delta' => 5,    
      '#title' => $component['#title'],
      '#default_value' => $component['#weight'],
    );
    $form['gallerix_layout'][$component['#id']]['display'] = array(
      '#type' => 'checkbox', 
      '#title' => t("Enabled"),
      '#default_value' =>  $component['#display'],
    );           
  }

  $form['gallerix_style'] = array(
    '#type' => 'fieldset',
    '#title' => t('Style Options'),
  );
  $form['gallerix_style']['gallerix_style'] = array(
    '#type' => 'select',
    '#title' => t('CSS Stylesheet'),
    '#description' => t('Select a style to use for Gallerix. Two styles are included by default, but select custom if you wish to use your own stylesheet'),  
    '#options' => array('standard.css' => t('Standard'), 'edgeless.css' => t('Edgeless'), 'custom' => t('Custom')), 
    '#default_value' => variable_get('gallerix_style', 'standard.css'),
  );
  $form['gallerix_style']['gallerix_style_path'] = array(
    '#type' => 'textfield',
    '#title' => t('Custom Stylesheet Path'),
    '#description' => t("If you choose to use your own stylesheet, enter the path where the stylesheet can be found. Don't forget that icons need to be relative to the stylesheet, 
                         so copy those over if necesssary, unless you are providing your own."),  
    '#disabled' => (variable_get('gallerix_style', 'standard.css') != 'custom'),
    '#default_value' => variable_get('gallerix_style_path', ''),
  );  

    
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit')
  );
  
  
  return $form;

}

function theme_gallerix_component_settings($form) {
  
  $header = array(t('Component'), t('Weight'), t('Display'));
  $rows = array();

  foreach(element_children($form) as $key) {
    //Remove titles from the select boxes.
    unset($form[$key]['weight']['#title']);
    unset($form[$key]['display']['#title']);
    
    //Extrac the title for each component, then unset it.
    $title = $form[$key]['title']['#value'];
    unset($form[$key]['title']);
    
    
    $rows[] = array (
      $title,
      drupal_render($form[$key]['weight']),
      drupal_render($form[$key]['display']),
    );
  }
  
  return theme('table', $header, $rows);
}


function gallerix_display_settings_validate($form, &$form_state) {

  if ($form_state['values']['gallerix_thumbnail_number'] != strval(intval($form_state['values']['gallerix_thumbnail_number']))) {
    form_set_error('gallerix_thumbnail_number', t('You must enter an number.'));
  }
  elseif (intval($form_state['values']['gallerix_thumbnail_number']) == 1 || intval($form_state['values']['gallerix_thumbnail_number']) == 2 || intval($form_state['values']['gallerix_thumbnail_number']) < 0) {
    form_set_error('gallerix_thumbnail_number', t('You must use at least 3 thumbnails. You may set to 0 to disable thumbnails.'));  
  }

}

function gallerix_display_settings_submit($form, &$form_state) {
  
  $weights = array();
  $display = array();
  
  foreach($form_state['values']['gallerix_layout'] as $key => $component) {
    $weights[$key] = $component['weight'];
    $display[$key] = $component['display'];
  }
  
  
  unset($form_state['values']['gallerix_layout']);
  
  variable_set('gallerix_layout_weights', $weights);
  variable_set('gallerix_layout_display', $display);

  cache_clear_all(NULL, 'cache_gallerix');
  
  system_settings_form_submit($form, $form_state);
  
}



function gallerix_admin_settings() {
  $sizes = gallerix_sizes();

  // Dummy to add a blank at the bottom of the table.
  $sizes[''] = array( 
    'name' => '',
    'width' => '',
    'height' => '',
    'ratio' => 0,
  );
  
  // Resolution Options
  $form['gallerix_sizes'] = array(
    '#type' => 'fieldset',
    '#title' => t('Resolutions'),
    '#theme' => 'gallerix_sizes_table',
    '#tree' => TRUE,
    '#description' => t("You may add more sizes to build for each picture submitted. If you want the picture to be resized exactly to the proportions,
                         check the Maintain Ratio box. If you don't check the box, pictures will only be scaled to fit given proportions."),
  ); 
  
  
  foreach ($sizes as $name => $size) {

    $entry = array();
    $entry['label'] = array(
      '#type' => 'textfield',
      '#default_value' => $size['label'],
      '#size' => 20,
    );
    $entry['name'] = array(
      '#type' => 'textfield',
      '#size' => 20,
      '#value' => $name,
      '#disabled' => $name == 'thumbnail' || $name == 'frame',
    );
    $entry['width'] = array(
      '#type' => 'textfield',
      '#size' => 5,
      '#default_value' => $size['width'],
    );
    $entry['height'] = array(
      '#type' => 'textfield',
      '#size' => 5,
      '#default_value' => $size['height'],      
    );     
    $entry['ratio'] = array(
      '#type' => 'checkbox',
      '#default_value' => $size['ratio'],      
    );    
    
    $form['gallerix_sizes'][] = $entry;  
  
  }
   
  // Source Options
  $form['gallerix_sources'] = array(
    '#type' => 'fieldset',
    '#title' => t('Picture Sources'),
  );
  $form['gallerix_sources']['gallerix_upload_number'] = array(
    '#type' => 'textfield',
    '#title' => t('Number of Upload Fields'),
    '#description' => t('Controls the number of file upload fields available to users at the same time. Set to 0 to disable file upload.'),
    '#size' => 2,
    '#default_value' => variable_get('gallerix_upload_number', 1)   
  );   
  $form['gallerix_sources']['gallerix_allow_archives'] = array(
    '#type' => 'checkbox',
    '#title' => t('Allow ZIP'),
    '#disabled' => !extension_loaded ('zip'),
    '#description' => t('When enabled, users will be able to upload ZIP archive files as well as images. This option is disabled if your PHP installation does not have the ZIP library.'),
    '#size' => 2,
    '#default_value' => variable_get('gallerix_allow_archives', false)   
  );   
  $form['gallerix_sources']['gallerix_repository'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable Repository.'),
    '#description' => t('Enabling the repository will provide a common place to upload your pictures using FTP. 
                         This is very useful if you are not using per-user albums, or you have a site with a controlled set of a few trusted users. 
                         When enabled, simply place picture files inside files/gallerix/repository, and they will show up whenever you are adding pictures to your albums. '),
    '#default_value' => variable_get('gallerix_repository', 0)
  );
  $form['gallerix_sources']['gallerix_delete_repository'] = array(
    '#type' => 'checkbox',
    '#title' => t('Delete From Repository.'),
    '#description' => t('When enabled, files will be moved to the repository to the album folder. If disabled, a copy will be made instead and the original files will be left untouched in the repository folder.'),
    '#default_value' => variable_get('gallerix_delete_repository', FALSE)
  );  
 
  
  // Insertion Options
  $form['gallerix_metadata'] = array(
    '#type' => 'fieldset',
    '#title' => t('Metadata Options'),
  );  
  $form['gallerix_metadata']['gallerix_extract_exif'] = array(
    '#type' => 'checkbox',
    '#title' => t('Extract EXIF Data'),
    '#disabled' => !function_exists('exif_read_data'),
    '#description' => t('Information such as Date Taken and Image Description are stored inside each file. If you enable this option, Gallerix will try to extract EXIF data from pictures. 
                         Sorting by dates only works if this feature is enabled. Note that this feature is automatically disabled if your PHP installation does not support EXIF extraction.'),
    '#default_value' => variable_get('gallerix_extract_exif', 0)
  );
  $form['gallerix_metadata']['gallerix_extract_iptc'] = array(
    '#type' => 'checkbox',
    '#title' => t('Extract IPTC Tags'),
    '#description' => t("Use this option to have Gallerix attempt to extract IPTC keywords from the files. This is very useful if you use Photoshop Elements or Photoshop to tag your files. 
                         Captions for pictures will be extracted from IPTC data and linked to pictures. Users can then override this caption if they wish to do so."),
    '#default_value' => variable_get('gallerix_extract_iptc', 0)
  );
  
  // Security Options
  $form['gallerix_security'] = array(
    '#type' => 'fieldset',
    '#title' => t('Gallerix Security'),
  );  
  $form['gallerix_security']['gallerix_secure_mode'] = array(
    '#type' => 'checkbox',
    '#title' => t('Secure Mode'),
    '#description' => t('Overall, secure mode tries to ensure that users only view pictures that belong to albums they are allowed to see. Remember, actual album access is not controlled. Use a Node Access module for this.'),
    '#default_value' => variable_get('gallerix_secure_mode', 0)
  );

  
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit')
  );
  
  
  return $form;
}


function theme_gallerix_sizes_table($form) {

  $header = array(t('Label'), t('Name'), t('Width'), t('Height'), t('Maintain Ratio'));
  $rows = array();
  
  foreach (element_children($form) as $key) {
    $rows[] = array(
      drupal_render($form[$key]['label']),        
      drupal_render($form[$key]['name']),
      drupal_render($form[$key]['width']),
      drupal_render($form[$key]['height']),
      drupal_render($form[$key]['ratio']),
    );
  }

  return theme('table',  $header, $rows);
}





function gallerix_admin_settings_validate($form_id, &$form_state) {

  $names = array();
  
  foreach ($form_state['values']['gallerix_sizes'] as $key => $size) {

    if ($size['name'] && $size['label']) {
      if (in_array($size['name'], $names)) {
        form_set_error('gallerix_sizes][' . $key . '][name', t('The name is already taken.'));
      }
      if (!preg_match("|^[0-9]+$|", $size['width'])) {
        form_set_error('gallerix_sizes][' . $key . '][width', t('Width must be a positive number.'));
      }
      if (!preg_match("|^[0-9]+$|", $size['height'])) {
        form_set_error('gallerix_sizes][' . $key . '][height', t('Height must be a positive number.'));
      }
      if (!preg_match("|^[a-z]+$|", $size['name'])) {
        form_set_error('gallerix_sizes][' . $key . '][name', t('Names can only contain lowercase letters. No spaces, underscores, or dashes.'));
      }
      
      $names[] = $size['name'];
    }
    elseif ($size['name']) {
        form_set_error('gallerix_sizes][' . $key . '][label', t('A label is required.'));      
    }
    elseif ($size['label']) {
        form_set_error('gallerix_sizes][' . $key . '][name', t('An internal name is required.'));         
    }
    
  }
}



function gallerix_admin_settings_submit($form_id, &$form_state) {

  foreach ($form_state['values']['gallerix_sizes'] as $key => $size) {
    if ($size['name']) {
      $name = $size['name'];
      unset($size['name']);
      
      $sizes[$name] = $size;
    }
  }
  
  variable_set('gallerix_sizes', $sizes);

  unset($form_state['values']['gallerix_sizes']);
  
  cache_clear_all(NULL, 'cache_gallerix');
  
  system_settings_form_submit($form_id, $form_state);
  
}



/**
 * Implementation of hook_form_alter().
 *
 * Add a Gallerix form to the performance settings page.
 *
 */
function gallerix_form_alter($form_id, &$form) {

  if ($form_id == 'system_performance_settings') {
    $form['gallerix'] = array(
      '#type' => 'fieldset',
      '#title' => t('Gallerix Cache'),
      '#description' => t("Enabling cache can speed up picture fetching. If you're experiencing strange behavior, turn this feature off."),
      '#weight' => 0,
    );
    $form['gallerix']['gallerix_cache'] = array(
      '#type' => 'radios',
      '#title' => t('Cache'),
      '#options' => array(t('Disabled'), t('Enabled')),
      '#default_value' => variable_get('gallerix_cache', 0),
    );
    
  }
}




/**
 * Provides means to upload pictures into an album.
 *
 */
function gallerix_add_pictures_form(&$form_state, $node) {

  drupal_set_title(t('Add Pictures'));
  
  //Repositories.
  $common_repository = file_directory_path() . '/gallerix/repository' ;
  
  $upload_files = variable_get('gallerix_upload_number', 1); 
  $archive_allowed = variable_get('gallerix_allow_archives', false);

  $extensions = $archive_allowed ? 'ZIP|zip' : '';
  $allowed_files = '.+\.(jpe?g|png|gif|JPE?G|PNG|GIF' . $extensions . ')';
  
  $common_files = variable_get('gallerix_repository', 0) ? file_scan_directory($common_repository, $allowed_files) : 0;

  
  $album_pictures = db_query('SELECT pid, path, name, caption, original_name FROM {gallerix_pictures} WHERE nid = %d ORDER BY sort', $node->nid);
  
  $form = array(); 
  $form['#tree'] = TRUE;
  
  // We use this as a placeholder to tell the submit function what to do.
  $actions = array();
  
  // We want to pass the node ID.
  $form['node_id'] = array(
    '#type' => 'value',
    '#value' => $node->nid,
  );
  $form['#attributes'] = array("enctype" => "multipart/form-data");
     
  // Manual Upload  
  if ($upload_files) {
    $form['gallerix_upload'] = array(
      '#type' => 'fieldset',
      '#title' => t('From Upload'),
      '#tree' => FALSE,
    );
    

    
    for ($x = 1; $x <= $upload_files; $x++) {
      
      if ($upload_files == 1) {
        $upload_text = t('Upload File');
      }
      else {
        $upload_text = t('Upload File !field_number', array('!field_number' => $x));
      }
    
      $form['gallerix_upload']['upload_' . $x] = array(
        '#type' => 'file',
        '#title' => $upload_text,
        '#size' => 40,
        '#description' => t('Select an image to upload. ') . ($archive_allowed ? t('You may also upload a ZIP file.') : ''),
        '#default_value' => '',
      );
    }
  }
  // Only display the "Add From Common Repository" form if there are any files to add.
  if ($common_files) {
    $actions['repository'] = TRUE; //Process repository.
    foreach($common_files as $file) {   
      $form['gallerix_repository']['checkboxes'][] = array(
        '#type' => 'checkbox',
        '#title' => $file->basename,
        '#collapsible' => TRUE,
      );
      $form['gallerix_repository']['files'][] = array(
        '#type' => 'value',
        '#value' => array('filename' => $file->filename, 'basename' => $file->basename, 'filesize' => filesize($file->filename)),
      );     
    }
  }
 
  
  //Let the submit function know what to process.
  $form['actions'] = array(
    '#type' => 'value',
    '#value' => $actions
  );
  
  
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit')
  ); 


  return $form;
}



/**
 * Themes the add form into a table.
 *
 */
function theme_gallerix_add_pictures_form($form) {
  
  $node = node_load($form['node_id']['#value']);
  $upload_files = variable_get('gallerix_upload_number', 1); 
  $paths = _gallerix_album_paths($node, true);
  
  $header = array(theme('table_select_header_cell'), t('Picture'), t('Caption'));
  $rows = array();
  
  $header = array(theme('table_select_header_cell'), t('File Name'), t('File Size'));
  $rowsAdd = array();
  
  foreach(element_children($form['gallerix_repository']['files']) as $key) {
     $basename = $form['gallerix_repository']['files'][$key]['#value']['basename'];
     $filesize = $form['gallerix_repository']['files'][$key]['#value']['filesize'];
     $filesize = format_size($filesize);
     
     unset($form['gallerix_repository']['checkboxes'][$key]['#title']);

     $rows[] = array(
      drupal_render($form['gallerix_repository']['checkboxes'][$key]),
      $basename,
      $filesize
     );
  }
 

  $output = '';
  
  if ($form['actions']['#value']['repository']) {
    $output .= '<h3>Repository Files</h3>';
    $output .= theme('table', $header, $rows);  
  }
  
  $output .= drupal_render($form['submit']);
  
  //Put the upload field on top.
  return drupal_render($form) . $output;  
  
}



/**
 * Figure out what's been uploaded and update the album with the new pictures.
 *
 */
function gallerix_add_pictures_form_submit($form_id, &$form_state) {

  $node = node_load($form_state['values']['node_id']);
  $paths = _gallerix_album_paths($node, true);

  $album_directory = $paths['album'];
  
  $rebuild = FALSE;
  $rebuild = FALSE;
  
  // Load in the settings. 
  $extract_exif = variable_get('gallerix_extract_exif', 0);
  $fields_to_extract = $extract_exif ? variable_get('gallerix_fields_to_extract', 0) : array();
  $delete_repository_files = variable_get('gallerix_delete_repository', FALSE);
  $upload_files = variable_get('gallerix_upload_number', 1); 
  $archive_allowed = variable_get('gallerix_allow_archives', false);
  
  $files = array();
    
  if ($upload_files) {
    for ($x = 1; $x <= $upload_files; $x++) {
     
     
      if ($file = file_save_upload('upload_' . $x, array(), file_directory_path(), FILE_EXISTS_RENAME)) { 
      
        // We don't want to use Drupal's file system.
        db_query('DELETE FROM {files} WHERE fid = %d', $file->fid);
        
        if ($temp_files = gallerix_process_file($file->filepath, $paths['original'], TRUE)) {
          $files = array_merge($temp_files, $files);       
        }
        else {
          file_delete($file->filepath);  
        }    
     
      }
    }  
    
    
  }        
  
  // Move files from repository to album.
  if ($form_state['values']['actions']['repository']) {
    foreach($form_state['values']['gallerix_repository']['checkboxes'] as $key => $checked) {
      if ($checked) {

        $source = $form_state['values']['gallerix_repository']['files'][$key]['filename'];
        $destination = $paths['original'] . '/' . $form_state['values']['gallerix_repository']['files'][$key]['basename'];
        
        $file = new stdClass();     
        $file->filename = $form_state['values']['gallerix_repository']['files'][$key]['basename'];
        $file->filepath = $source;
        
        if ($temp_files = gallerix_process_file($source, $paths['original'], $delete_repository_files)) {
          $files = array_merge($temp_files, $files);         
        }


      }

    }
  }
  
  
  
  // For each added file, make a new entry in the database.
  foreach($files as $file) {
    $original_name = basename($file);
    
    $secure_path = _gallerix_secure_file($file);
    $secure_name = basename($secure_path);
    
    db_query("INSERT INTO {gallerix_pictures} (nid, uid, path, name, original_name, added, created, caption) VALUES (%d, %d, '%s', '%s', '%s', %d, %d, '%s')", $node->nid, $node->uid, 
            $secure_path, $secure_name, $original_name, time(), time(), '');
            
        
  }
  
  cache_clear_all(NULL, 'cache_gallerix');
  
  if (count($files)) {
    $form_state['redirect'] = 'node/' . $node->nid . '/pictures/build';
  }
}




/**
 * Provides an AJAX based management form for pictures in an album.
 *
 */
function gallerix_manage_pictures_form(&$form_state, $node) {

  drupal_set_title(t('Manage Pictures'));
    
  //Load common.js.  
  gallerix_load_js();  
    
  //Include management JavaScript and CSS.
  $path = drupal_get_path('module', 'gallerix');
  drupal_add_js($path . '/js/management.js');
  drupal_add_css($path . '/management.css');

  $album_pictures = db_query('SELECT pid, path, name, caption, original_name FROM {gallerix_pictures} WHERE nid = %d ORDER BY sort', $node->nid);
  
  $form = array(); 
  $form['#tree'] = TRUE;
  
  //We use this as a placeholder to tell the submit function what to do.
  $actions = array();
  
  //We want to pass the node ID.
  $form['node_id'] = array(
    '#type' => 'value',
    '#value' => $node->nid,
  );
  $form['album_repository'] = array(
    '#type' => 'value',
    '#value' => $album_repository
  );

  $count = 0;
  
  $index = array();
  $pictures = array();
  $captions = array();

  $sort = $node->gallerix['sort'];
  $sort = ($sort == 'default') ? variable_get('gallerix_default_sort', 'ascending') : $sort;

  
  while($picture = db_fetch_object($album_pictures)) {
    $actions['album'] = TRUE; //Process album.  
    

    $form['gallerix_album']['files'][] = array(
      '#type' => 'value',
      '#value' => array(
        'filename' => $picture->path, 
        'basename' => $picture->name, 
        'pid' => $picture->pid, 
        'caption' => $picture->caption, 
        'original_name' => $picture->original_name,
      ),
    ); 
    $form['gallerix_album']['captions'][] = array(
      '#type' => 'textfield',
      '#title' => 'Caption',
      '#id' => 'gallerix-caption-field-' . $picture->pid,
      '#attributes' => array('class' => 'gallerix-caption-field'),
    );
    
    $index[] = $picture->pid;
    $pictures[$picture->pid] = $count;
    $captions[$picture->pid] = $picture->caption;
    $count++;      
  }

  drupal_add_js(array('gallerixManager' => array(
    'index' => $index,
    'pictures' => $pictures,
    'captions' => $captions,
    'count' => $count,
    'settings' => array(
      'deleteURL' => url('node/' . $node->nid . '/pictures/manage/delete/'),
      'submitURL' => url('node/' . $node->nid . '/pictures/manage/submit'),
      'reloadURL' => url('node/' . $node->nid . '/pictures', array('absolute' => TRUE)),
      'allowSorting' => $sort == 'custom',
    ),  
  
  )), 'setting');
  
  
  
  
  //Let the submit function know what to process.
  $form['actions'] = array(
    '#type' => 'value',
    '#value' => $actions
  );
  
  $form['save'] = array(
    '#type' => 'button',
    '#value' => t('Save Changes'),
    '#attributes' => array('class' => 'gallerix-management-save'),
  );   

    
  return $form;   
}



/**
 * Themes the management form into a table and adds the action buttons.
 *
 */
function theme_gallerix_manage_pictures_form($form) {

  $node = node_load($form['node_id']['#value']);

  $upload_files = variable_get('gallerix_upload_number', 1); 
  $paths = _gallerix_album_paths($node, true);
  $save = drupal_render($form['save']);
  
  $sort = $node->gallerix['sort'];
  $sort = ($sort == 'default') ? variable_get('gallerix_default_sort', 'ascending') : $sort;
  
  if ($sort == 'custom') {
    $up = theme('image', theme('gallerix_icon', 'up.png'), t('Up'), t('Click to shift up.'));
    $down = theme('image', theme('gallerix_icon', 'down.png'), t('Down'), t('Click to shift down.'));
    $top = theme('image', theme('gallerix_icon', 'top.png'), t('Top'), t('Click to shift to the top.'));
    $bottom = theme('image', theme('gallerix_icon', 'bottom.png'), t('Bottom'), t('Click to shift to the bottom.'));  
  }
  
  $delete = theme('image', theme('gallerix_icon', 'delete.png'), t('Delete'), t('Click to mark for deletion.'));
  $restore = theme('image', theme('gallerix_icon', 'restore.png'), t('Restore'), t('Click to restore this picture.'));

   
  $header = array(t('Picture'), t('Caption'), t('Actions'));
  $rows = array();
  
  $count = 0;
      
  foreach(element_children($form['gallerix_album']['files']) as $key) {
     $pid = $form['gallerix_album']['files'][$key]['#value']['pid'];  
     $basename = $form['gallerix_album']['files'][$key]['#value']['basename'];
     
     $picture = gallerix_load_picture($pid);
     
     $thumbnail_attributes = array(
       'class' => 'gallerix-thumbnail-field', 
       'id' => 'gallerix-thumbnail-field-' . $pid, 
       'height' => '40',
       'style' => 'margin: 2px; cursor: pointer;'
     );
     
     $thumbnail = theme('image', $picture->thumbnail, $alt = '', $basename, $thumbnail_attributes, FALSE);     

     unset($form['gallerix_album']['checkboxes'][$key]['#title']);
     unset($form['gallerix_album']['captions'][$key]['#title']);
     unset($form['gallerix_album']['checkboxes'][$key]);
     

     $actions = '';
     $actions .= l($top, '#', array('attributes' => array('id' => 'gallerix-top-field-' . $pid, 'class' => 'gallerix-top-field  gallerix-action'), 'html' => TRUE));     
     $actions .= l($up, '#', array('attributes' => array('id' => 'gallerix-up-field-' . $pid, 'class' => 'gallerix-up-field  gallerix-action'), 'html' => TRUE));    
     $actions .= l($down, '#', array('attributes' => array('id' => 'gallerix-down-field-' . $pid, 'class' => 'gallerix-down-field  gallerix-action'), 'html' => TRUE));
     $actions .= l($bottom, '#', array('attributes' => array('id' => 'gallerix-bottom-field-' . $pid, 'class' => 'gallerix-bottom-field  gallerix-action'), 'html' => TRUE));      
     $actions .= l($delete, '#', array('attributes' => array('id' => 'gallerix-delete-field-' . $pid, 'class' => 'gallerix-delete-field  gallerix-action'), 'html' => TRUE));
     $actions .= l($restore, '#', array('attributes' => array('id' => 'gallerix-restore-field-' . $pid, 'class' => 'gallerix-restore-field  gallerix-action', 'style' => 'display: none;'), 'html' => TRUE));
          
     $row_data = array(
      $thumbnail,
      drupal_render($form['gallerix_album']['captions'][$key]),
      $actions, 
     );
          
     $rows[] = array(
      'data' => $row_data,
      'class' => 'gallerix-management-row',
      'id' => 'gallerix-management-row-' . $pid,
     );
     
     $count++;
  }

  $output = '';
  $output .= theme('gallerix_message_box');
  
  $output .= theme('gallerix_manage_pictures_help'); 
  $output .= $save;
  $output .= theme('table', $header, $rows);
  $output .= $save;
  
  return drupal_render($form) . $output;

}


function theme_gallerix_manage_pictures_help() {
  $output = '';
  $output .= '<p>';
  $output .= t('Customize your album here. You can use the tab key to shift quickly between pictures.');
  $output .= '<br />';
  $output .= t('If you chose custom ordering, hold down the CTRL key while pressing up or down to reorder your pictures quickly.');
  $output .= '<br />';
  $output .= t('Remember to save changes!');
  $output .= '</p>';
  
  return $output;
}


/**
 * Uses AJAX to handle form submission. Note that this is NOT the same as
 * gallerix_manage_pictures_form_submit() which is unused in this implementation.
 *
 */
function gallerix_manage_form_submit() {
  
  
  global $user;
  
  cache_clear_all(NULL, 'cache_gallerix');
  
  
  foreach ($_POST as $pid => $content) {
    $content = explode("|#|", $content);
    
    //Sanity check.
    $pid = check_plain($pid);
    $action = $content[0];
    
    
    $picture = gallerix_load_picture($pid);

    //Unauthorized request.
    if ($user->uid != $picture->uid) {
      
      $result = array(
        'status' => 'error',
        'message' => t("Unauthorized picture modification attempt. Your IP has been logged."),
      );
      
      watchdog('gallerix', 'Unauthorized picture modification attempt for picture !picture', array('!picture' => $picture->pid), WATCHDOG_WARNING);
            
      print gallerix_to_js($result);
      exit();
    }

    
    
    if ($action == 'sort') {

      $sort = (int) check_plain($content[1]);
      $caption = check_plain($content[2]);
      $caption = trim($caption);
            
      //Sorting starts at 1, not 0.
      $sort++;
           
      db_query("UPDATE {gallerix_pictures} SET caption = '%s', sort = %d WHERE pid = %s", $caption, $sort, $picture->pid);     
    }
    else if ($action == 'delete') {
       gallerix_delete_picture($pid);
    }  
  
  }
  
  
  db_query('SELECT nid FROM {gallerix_pictures} WHERE nid = %d', $picture->nid);
  $count = db_affected_rows();
  
  if ($count) {
    $result = array(
      'status' => 'success',
      'message' => t("Pictures updated successfully."),
    );  
  }
  else {
    $result = array(
      'status' => 'reload',
      'message' => t("All pictures have been deleted."),
    );    
  }
  
  
  print gallerix_to_js($result);
  
  exit();
}




/** 
 * Deletes a picture from an album through the management form.
 *
 */
function gallerix_manage_form_delete($pid) {
  $picture = gallerix_load_picture($pid);
  
  gallerix_delete_picture($picture);
  

}






/***************************** Sorting ********************************/



/**
 * Sort pictures according to 5 different cases.
 *
 */
function gallerix_sort_album(&$node) {
  $counter = 0;
  $sort_order = $node->sort_order;
  $sort_order = $sort_order ? $sort_order : $node->gallerix['sort'];
  $sort_order = $sort_order ? $sort_order : 'default';
  $sort_order = ($sort_order == 'default') ? variable_get('gallerix_default_sort', 'ascending') : $sort_order;

  switch($sort_order) {
    case 'ascending':
      _gallerix_sort_pictures_ascending($node->nid);
      break;
    case 'descending':
      _gallerix_sort_pictures_descending($node->nid);
      break;
    case 'random':
      _gallerix_sort_pictures_random($node->nid);
      break;
    case 'filename':
      _gallerix_sort_pictures_filename($node->nid);
      break;
    case 'custom':
      _gallerix_sort_pictures_custom($node->nid);
      break;
  }
  
  cache_clear_all(NULL, 'cache_gallerix');

}


/**
 * Sort by date taken ascending.
 *
 */
function _gallerix_sort_pictures_ascending($nid) {
  $pictures = db_query("SELECT pid FROM {gallerix_pictures} WHERE nid = %d ORDER BY created", $nid);
  $counter = 1;
  
  while($picture = db_fetch_object($pictures)) {
    db_query("UPDATE {gallerix_pictures} SET sort = %d WHERE pid = %d", $counter, $picture->pid);   
    $counter++;
  }  
}


/**
 * Sort by date taken descending.
 *
 */
function _gallerix_sort_pictures_descending($nid) {
  $pictures = db_query("SELECT pid FROM {gallerix_pictures} WHERE nid = %d ORDER BY created DESC", $nid);
  $counter = 1;
  
  while($picture = db_fetch_object($pictures)) {
    db_query("UPDATE {gallerix_pictures} SET sort = %d WHERE pid = %d", $counter, $picture->pid);   
    $counter++;
  }  
}


/**
 * Sort randomly.
 *
 */
function _gallerix_sort_pictures_random($nid) {
  $pictures = db_query("SELECT pid FROM {gallerix_pictures} WHERE nid = %d ORDER BY created DESC", $nid);
  $collisions = array();
  
  while($picture = db_fetch_object($pictures)) {
    $random = rand() % 100;
    db_query("UPDATE {gallerix_pictures} SET sort = %d WHERE pid = %d", $random, $picture->pid);   
  }  
  
  _gallerix_sort_pictures_custom($nid);

}


/**
 * Sort by filename ascending.
 *
 */
function _gallerix_sort_pictures_filename($nid) {
  $pictures = db_query("SELECT pid FROM {gallerix_pictures} WHERE nid = %d ORDER BY name", $nid);
  $counter = 1;
  
  while($picture = db_fetch_object($pictures)) {
    db_query("UPDATE {gallerix_pictures} SET sort = %d WHERE pid = %d", $counter, $picture->pid);   
    $counter++;
  }  
}


/**
 * Custom sort just makes sure that there are no gaps in the 'sort' field.
 *
 */
function _gallerix_sort_pictures_custom($nid) {

  $pictures = db_query("SELECT pid FROM {gallerix_pictures} WHERE nid = %d ORDER BY sort", $nid);
  $counter = 1;
  
  while($picture = db_fetch_object($pictures)) {
    db_query("UPDATE {gallerix_pictures} SET sort = %d WHERE pid = %d", $counter, $picture->pid);   
    $counter++;
  }  

}


